package com.simba.server.task;

import com.simba.server.commands.impl.fetch.FetchBoxPackCmd;
import com.simba.server.commands.impl.fetch.FetchPacketByBoxCodeCmd;
import com.simba.server.commands.impl.update.RenewBoxPackCmd;
import com.simba.server.commands.impl.web.WebPackSlotCmd;
import com.simba.server.components.CommandExecutor;
import org.apache.log4j.Logger;



import com.simba.common.log.LogUtil;

import com.simba.server.components.data.BoxInfo;

public class BoxPackOfferTask extends Thread
{
	private final static Logger logger = Logger.getLogger(BoxPackOfferTask.class);
	private static final int REQUEST_INTERVAL = 1000;

	public BoxPackOfferTask()
	{
		this.setName("Box-Pack-Offer-Task");
	}

	@Override
	public void run()
	{
		while (!Thread.currentThread().isInterrupted())
		{
			try
			{
				this.getUploadBoxInfo();
				Thread.sleep(BoxPackOfferTask.REQUEST_INTERVAL);
			}
			catch (Exception ex)
			{
				if (ex instanceof InterruptedException)
				{
					Thread.currentThread().interrupt();
				}
				LogUtil.LogError(BoxPackOfferTask.logger,
						"Catch an exception [" + ex.getMessage() + "]");
			}
		}
	}

	private void getUploadBoxInfo()
	{
		BoxInfo boxInfo = new BoxInfo();
		Boolean ret = CommandExecutor.executorSqlCommand(FetchBoxPackCmd.NAME, boxInfo,false);
		if (!ret)
		{
			return;
		}

		if (boxInfo.getId() == 0){
			return;
		}

		if (boxInfo.getBoxCode() == null || boxInfo.getBoxCode().equals("")||boxInfo.getBoxCode().equals("none"))
		{
			boxInfo.setUploadFlag(-1);
			CommandExecutor.executorSqlCommand(RenewBoxPackCmd.NAME, boxInfo,false);
			return;
		}

		ret = CommandExecutor.executorSqlCommand(FetchPacketByBoxCodeCmd.NAME, boxInfo,false);
		if (!ret)
		{
			return;
		}

		if (boxInfo.getMails().isEmpty())
		{
			boxInfo.setUploadFlag(-1);
			CommandExecutor.executorSqlCommand(RenewBoxPackCmd.NAME, boxInfo,false);
			return;
		}

		int uploadNum = boxInfo.getUploadNum() + 1;
		boxInfo.setUploadNum(uploadNum);
		boxInfo.setUploadFlag(1);

		ret = CommandExecutor.executorWebCommand(WebPackSlotCmd.NAME, boxInfo,false);
		if (!ret)
		{
			boxInfo.setUploadFlag(0);
		}

		CommandExecutor.executorSqlCommand(RenewBoxPackCmd.NAME, boxInfo,false);
	}
}
